package com.ego.controller;

import com.ego.dao.CartDao;
import com.ego.dao.impl.CartDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 袁梦达 2019012364
 */
@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {

    private CartDao cartDao = new CartDaoImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userNumber = String.valueOf(getServletContext().getAttribute("userNumber"));
        if(userNumber == null){
            //未登录
            response.getWriter().print(false);
        }else {
            InputStream is = request.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1){
                stringBuffer.append(new String(bytes, 0, len));
            }
            String[] strings = stringBuffer.toString().split(",");
            String opt = strings[0];
            Integer productId = Integer.valueOf(strings[1]);
            Boolean result;
            if("add".equals(opt)){
                result = cartDao.addProduct(userNumber, productId);
            }else {
                result = cartDao.removeProduct(userNumber, productId);
            }
            response.getWriter().print(result);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
